<template>
  <el-card>
    <template #header>
      <!-- <span style="color: #3998a9;">文件管理</span> -->
      <h2 style="color: #3998a9;">文件管理</h2>
      <div style="float:right;display:flex;gap:8px;align-items:center; margin-top: 40PX;">
        <el-button v-if="currentPath.length" @click="goBackFolder">返回上级</el-button>
        <el-button type="primary" @click="goUpload">文件上传</el-button>
      </div>
    </template>
    <el-form :inline="true" style="margin-bottom:16px">
      <el-form-item label="新建文件夹">
        <el-input v-model="newFolder" placeholder="文件夹名称" style="width:180px" />
        <el-button type="success" @click="createFolder">创建</el-button>
      </el-form-item>
      <el-form-item label="当前位置" style="margin-left:24px">
        <span>{{ currentPathLabel }}</span>
      </el-form-item>
    </el-form>
    <el-table :data="fileList" style="width:100%" border>
      <el-table-column label="文件名">
        <template #default="scope">
          <span v-if="scope.row.type==='folder'" style="cursor:pointer;color:#409EFF" @click="enterFolder(scope.row)">
            <i class="el-icon-folder-opened"></i> {{scope.row.name}}
          </span>
          <span v-else>{{scope.row.name}}</span>
        </template>
      </el-table-column>
      <el-table-column prop="path" label="路径" />
      <el-table-column prop="type" label="类型" width="100" />
      <el-table-column prop="size" label="大小" width="100" />
      <el-table-column prop="uploadTime" label="上传时间" width="160" />
      <el-table-column prop="owner" label="拥有者" width="100" />
      <el-table-column prop="actions" label="操作" width="180">
        <template #default="scope">
          <el-button v-if="scope.row.type!=='folder'" type="primary" size="small" @click="downloadFile(scope.row)">下载</el-button>
          <el-button v-if="scope.row.type==='folder' && isAdmin" type="warning" size="small" @click="editFolder(scope.row)">编辑</el-button>
          <el-button v-if="isAdmin" type="danger" size="small" @click="deleteFile(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
  </el-card>
  <el-dialog v-model="editDialogVisible" title="编辑文件夹名称" width="400px">
    <el-input v-model="editFolderName" placeholder="请输入新文件夹名称" />
    <template #footer>
      <el-button @click="editDialogVisible = false">取消</el-button>
      <el-button type="primary" @click="confirmEditFolder">确定</el-button>
    </template>
  </el-dialog>
</template>

<script setup>
// 编辑文件夹弹窗相关
const editDialogVisible = ref(false)
const editFolderName = ref('')
const editFolderObj = ref(null)

function editFolder(folder) {
  editFolderObj.value = folder
  editFolderName.value = folder.name
  editDialogVisible.value = true
}

function confirmEditFolder() {
  if (!editFolderName.value.trim()) {
    ElMessage.warning('文件夹名称不能为空')
    return
  }
  let storageList = JSON.parse(localStorage.getItem('fileList') || '[]')
  // 找到并更新
  const idx = storageList.findIndex(f => f.id === editFolderObj.value.id)
  if (idx !== -1) {
    storageList[idx].name = editFolderName.value
    // 路径也要同步更新
    const oldPath = storageList[idx].path
    const parentPath = storageList[idx].path.substring(0, storageList[idx].path.lastIndexOf('/'))
    storageList[idx].path = parentPath + '/' + editFolderName.value
    // 同步更新所有子项path
    const updateChildrenPath = (pid, oldParentPath, newParentPath) => {
      storageList.forEach(item => {
        if (item.parent === pid) {
          item.path = item.path.replace(oldParentPath, newParentPath)
          if (item.type === 'folder') updateChildrenPath(item.id, oldParentPath + '/' + item.name, newParentPath + '/' + item.name)
        }
      })
    }
    updateChildrenPath(storageList[idx].id, oldPath, storageList[idx].path)
    localStorage.setItem('fileList', JSON.stringify(storageList))
    loadFileList()
    ElMessage.success('文件夹名已更新')
    editDialogVisible.value = false
  }
}
import { ref, computed } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'

const router = useRouter()
const isAdmin = true // 可根据实际权限控制
const newFolder = ref('')
const fileList = ref([])
const currentPath = ref([]) // 目录层级数组

const getCurrentParent = () => {
  return currentPath.value.length ? currentPath.value[currentPath.value.length-1].id : null
}

const currentPathLabel = computed(() => {
  if (!currentPath.value.length) return '/'
  return '/' + currentPath.value.map(f=>f.name).join('/')
})

function loadFileList() {
  let storageList = JSON.parse(localStorage.getItem('fileList') || '[]')
  // 只显示当前目录下的内容
  const parent = getCurrentParent()
  let list = storageList.filter(f => (f.parent || null) === parent)
  fileList.value = list
}
loadFileList()

function goUpload() {
  // 记录当前目录id到sessionStorage，供上传页用
  const parent = getCurrentParent()
  sessionStorage.setItem('uploadParent', parent || '')
  router.push('/file/fileupload')
}

function createFolder() {
  if (!newFolder.value.trim()) {
    ElMessage.warning('请输入文件夹名称')
    return
  }
  // 生成唯一id
  const id = 'f_' + Date.now() + Math.floor(Math.random()*1000)
  const parent = getCurrentParent()
  const folderObj = {
    id,
    name: newFolder.value,
    type: 'folder',
    size: '-',
    owner: 'admin01',
    uploadTime: new Date().toLocaleString(),
    path: (currentPathLabel.value === '/' ? '/uploads' : '/uploads' + currentPathLabel.value) + '/' + newFolder.value,
    parent: parent
  }
  let storageList = JSON.parse(localStorage.getItem('fileList') || '[]')
  storageList.push(folderObj)
  localStorage.setItem('fileList', JSON.stringify(storageList))
  loadFileList()
  ElMessage.success('文件夹创建成功')
  newFolder.value = ''
}

function enterFolder(folder) {
  if (folder.isBack) return
  currentPath.value.push({id: folder.id, name: folder.name})
  loadFileList()
}

function goBackFolder() {
  currentPath.value.pop()
  loadFileList()
}

function downloadFile(file) {
  if (file.type === 'folder') {
    ElMessage.warning('文件夹不支持下载')
    return
  }
  let storageList = JSON.parse(localStorage.getItem('fileList') || '[]')
  const target = storageList.find(f => f.id === file.id)
  if (!target || !target.content) {
    ElMessage.error('文件内容不存在')
    return
  }
  const a = document.createElement('a')
  a.href = target.content
  a.download = target.name
  document.body.appendChild(a)
  a.click()
  document.body.removeChild(a)
}

function deleteFile(file) {
  ElMessageBox.confirm(`确认删除文件：${file.name}？`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    let storageList = JSON.parse(localStorage.getItem('fileList') || '[]')
    // 删除文件夹时递归删除子文件
    const removeChildren = (id) => {
      const children = storageList.filter(f => f.parent === id)
      for (const child of children) {
        storageList = storageList.filter(f => f.id !== child.id)
        if (child.type === 'folder') removeChildren(child.id)
      }
    }
    storageList = storageList.filter(f => f.id !== file.id)
    if (file.type === 'folder') removeChildren(file.id)
    localStorage.setItem('fileList', JSON.stringify(storageList))
    loadFileList()
    ElMessage.success('文件已删除')
  })
}
</script>
